package com.devenv.service;

import com.devenv.entity.UserStatistics;
import com.devenv.repository.UserStatisticsRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.*;

/**
 * 用户统计服务
 * <p>
 * 提供用户统计数据的管理和分析功能
 * </p>
 * 
 * @author DevEnv OpenSource Team
 * @version 1.0.0
 * @since 1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserStatisticsService {

    private final UserStatisticsRepository userStatisticsRepository;

    /**
     * 初始化用户统计信息
     */
    @Transactional
    public UserStatistics initializeUserStats(Long userId) {
        if (userStatisticsRepository.existsByUserId(userId)) {
            return userStatisticsRepository.findByUserId(userId).get();
        }

        UserStatistics stats = new UserStatistics();
        stats.setUserId(userId);
        stats.setTotalScriptsGenerated(0);
        stats.setTotalTemplatesCreated(0);
        stats.setTotalTemplatesUsed(0);
        stats.setTotalSoftwareSelected(0);
        stats.setTotalLoginDays(0);
        stats.setConsecutiveLoginDays(0);
        stats.setMaxConsecutiveLoginDays(0);
        stats.setTotalActiveDays(0);
        stats.setAvgSessionDurationMinutes(0);

        return userStatisticsRepository.save(stats);
    }

    /**
     * 获取用户统计信息
     */
    public UserStatistics getUserStatistics(Long userId) {
        return userStatisticsRepository.findByUserId(userId)
                .orElseGet(() -> initializeUserStats(userId));
    }

    /**
     * 获取统计概览
     */
    public Map<String, Object> getStatisticsOverview(Long userId) {
        UserStatistics stats = getUserStatistics(userId);
        Map<String, Object> overview = new HashMap<>();
        
        overview.put("userId", userId);
        overview.put("totalScriptsGenerated", stats.getTotalScriptsGenerated());
        overview.put("totalTemplatesCreated", stats.getTotalTemplatesCreated());
        overview.put("totalTemplatesUsed", stats.getTotalTemplatesUsed());
        overview.put("totalSoftwareSelected", stats.getTotalSoftwareSelected());
        overview.put("totalLoginDays", stats.getTotalLoginDays());
        overview.put("consecutiveLoginDays", stats.getConsecutiveLoginDays());
        overview.put("maxConsecutiveLoginDays", stats.getMaxConsecutiveLoginDays());
        overview.put("totalActiveDays", stats.getTotalActiveDays());
        overview.put("avgSessionDurationMinutes", stats.getAvgSessionDurationMinutes());
        overview.put("favoriteOs", stats.getFavoriteOs());
        overview.put("favoriteCategory", stats.getFavoriteCategory());
        overview.put("lastLoginDate", stats.getLastLoginDate());
        overview.put("firstLoginDate", stats.getFirstLoginDate());
        
        // 计算用户等级和活跃度
        overview.put("userLevel", stats.getUserLevel());
        overview.put("activityScore", stats.calculateActivityScore());
        overview.put("isActiveUser", stats.isActiveUser());
        
        return overview;
    }

    /**
     * 更新登录统计
     */
    @Transactional
    public void updateLoginStats(Long userId, LocalDate loginDate) {
        UserStatistics stats = getUserStatistics(userId);
        stats.updateLoginStats(loginDate);
        userStatisticsRepository.save(stats);
        
        log.debug("更新用户登录统计: userId={}, loginDate={}", userId, loginDate);
    }

    /**
     * 增加脚本生成次数
     */
    @Transactional
    public void incrementScriptGeneration(Long userId) {
        UserStatistics stats = getUserStatistics(userId);
        stats.incrementScriptGeneration();
        userStatisticsRepository.save(stats);
        
        log.debug("增加用户脚本生成次数: userId={}", userId);
    }

    /**
     * 增加模板创建次数
     */
    @Transactional
    public void incrementTemplateCreation(Long userId) {
        UserStatistics stats = getUserStatistics(userId);
        stats.incrementTemplateCreation();
        userStatisticsRepository.save(stats);
        
        log.debug("增加用户模板创建次数: userId={}", userId);
    }

    /**
     * 增加模板使用次数
     */
    @Transactional
    public void incrementTemplateUsage(Long userId) {
        UserStatistics stats = getUserStatistics(userId);
        stats.incrementTemplateUsage();
        userStatisticsRepository.save(stats);
        
        log.debug("增加用户模板使用次数: userId={}", userId);
    }

    /**
     * 增加软件选择次数
     */
    @Transactional
    public void incrementSoftwareSelection(Long userId, int count) {
        UserStatistics stats = getUserStatistics(userId);
        stats.incrementSoftwareSelection(count);
        userStatisticsRepository.save(stats);
        
        log.debug("增加用户软件选择次数: userId={}, count={}", userId, count);
    }

    /**
     * 更新用户活跃天数
     */
    @Transactional
    public void updateActiveDays(Long userId) {
        UserStatistics stats = getUserStatistics(userId);
        stats.updateActiveDays();
        userStatisticsRepository.save(stats);
        
        log.debug("更新用户活跃天数: userId={}", userId);
    }

    /**
     * 更新会话时长
     */
    @Transactional
    public void updateSessionDuration(Long userId, int sessionDurationMinutes) {
        UserStatistics stats = getUserStatistics(userId);
        stats.updateAvgSessionDuration(sessionDurationMinutes);
        userStatisticsRepository.save(stats);
        
        log.debug("更新用户会话时长: userId={}, duration={}分钟", userId, sessionDurationMinutes);
    }

    /**
     * 更新偏好操作系统
     */
    @Transactional
    public void updateFavoriteOs(Long userId, String os) {
        UserStatistics stats = getUserStatistics(userId);
        stats.setFavoriteOs(os);
        userStatisticsRepository.save(stats);
        
        log.debug("更新用户偏好操作系统: userId={}, os={}", userId, os);
    }

    /**
     * 更新偏好分类
     */
    @Transactional
    public void updateFavoriteCategory(Long userId, String category) {
        UserStatistics stats = getUserStatistics(userId);
        stats.setFavoriteCategory(category);
        userStatisticsRepository.save(stats);
        
        log.debug("更新用户偏好分类: userId={}, category={}", userId, category);
    }

    /**
     * 获取排行榜数据
     */
    public Map<String, Object> getLeaderboard() {
        Map<String, Object> leaderboard = new HashMap<>();
        
        // 脚本生成排行榜
        List<UserStatistics> scriptLeaders = userStatisticsRepository.findTopByScriptGeneration(
                org.springframework.data.domain.PageRequest.of(0, 10));
        leaderboard.put("scriptGeneration", scriptLeaders);
        
        // 模板创建排行榜
        List<UserStatistics> templateLeaders = userStatisticsRepository.findTopByTemplateCreation(
                org.springframework.data.domain.PageRequest.of(0, 10));
        leaderboard.put("templateCreation", templateLeaders);
        
        // 连续登录排行榜
        List<UserStatistics> loginLeaders = userStatisticsRepository.findTopByConsecutiveLogins(
                org.springframework.data.domain.PageRequest.of(0, 10));
        leaderboard.put("consecutiveLogins", loginLeaders);
        
        return leaderboard;
    }

    /**
     * 获取平台统计总览
     */
    public Map<String, Object> getPlatformOverview() {
        Map<String, Object> overview = new HashMap<>();
        
        // 总体统计
        overview.put("totalScriptsGenerated", userStatisticsRepository.sumTotalScriptsGenerated());
        overview.put("totalTemplatesCreated", userStatisticsRepository.sumTotalTemplatesCreated());
        overview.put("totalTemplatesUsed", userStatisticsRepository.sumTotalTemplatesUsed());
        
        // 热门操作系统
        List<Object[]> popularOs = userStatisticsRepository.findPopularOperatingSystems();
        overview.put("popularOperatingSystems", popularOs);
        
        // 热门分类
        List<Object[]> popularCategories = userStatisticsRepository.findPopularCategories();
        overview.put("popularCategories", popularCategories);
        
        // 用户行为分布
        Object[] scriptDistribution = userStatisticsRepository.getScriptGenerationDistribution();
        overview.put("scriptGenerationDistribution", scriptDistribution);
        
        return overview;
    }

    /**
     * 查找活跃用户
     */
    public List<UserStatistics> getActiveUsers(int days) {
        LocalDate since = LocalDate.now().minusDays(days);
        return userStatisticsRepository.findActiveUsersSince(since);
    }

    /**
     * 查找新手用户
     */
    public List<UserStatistics> getNewbieUsers(int activityThreshold) {
        return userStatisticsRepository.findNewbieUsers(activityThreshold);
    }

    /**
     * 查找需要激活提醒的用户
     */
    public List<UserStatistics> getInactiveUsers(int inactiveDays) {
        LocalDate threshold = LocalDate.now().minusDays(inactiveDays);
        return userStatisticsRepository.findInactiveUsers(threshold);
    }

    /**
     * 批量更新用户统计
     */
    @Transactional
    public void batchUpdateStats(Map<Long, Map<String, Integer>> userStatsMap) {
        for (Map.Entry<Long, Map<String, Integer>> entry : userStatsMap.entrySet()) {
            Long userId = entry.getKey();
            Map<String, Integer> updates = entry.getValue();
            
            UserStatistics stats = getUserStatistics(userId);
            
            if (updates.containsKey("scripts")) {
                for (int i = 0; i < updates.get("scripts"); i++) {
                    stats.incrementScriptGeneration();
                }
            }
            
            if (updates.containsKey("templates")) {
                for (int i = 0; i < updates.get("templates"); i++) {
                    stats.incrementTemplateCreation();
                }
            }
            
            if (updates.containsKey("software")) {
                stats.incrementSoftwareSelection(updates.get("software"));
            }
            
            userStatisticsRepository.save(stats);
        }
        
        log.info("批量更新用户统计完成，影响用户数: {}", userStatsMap.size());
    }
}
